package cn.wolfcode.handler;

import cn.wolfcode.domain.OrderInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.concurrent.TimeUnit;

@CanalTable("t_order_info")
@Component
@Slf4j
public class OrderInfoHandler implements EntryHandler<OrderInfo> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final static String ORDER_KEY = "seckill::orders:";

    @Override
    public void insert(OrderInfo orderInfo) {
        String json = JSON.toJSONString(orderInfo);
        log.info("[订单数据监听] 收到订单新增数据：{}", json);
        redisTemplate.opsForValue().set(ORDER_KEY + orderInfo.getOrderNo(), json, 30, TimeUnit.MINUTES);
    }

    @Override
    public void update(OrderInfo before, OrderInfo after) {
        String json = JSON.toJSONString(after);
        log.info("[订单数据监听] 收到订单修改数据-BEFORE：{}", JSON.toJSONString(before));
        redisTemplate.opsForValue().set(ORDER_KEY + after.getOrderNo(), json, 30, TimeUnit.MINUTES);
        log.info("[订单数据监听] 收到订单修改数据-AFTER：{}", json);
    }

    @Override
    public void delete(OrderInfo orderInfo) {
        log.info("[订单数据监听] 收到订单删除数据：{}", JSON.toJSONString(orderInfo));
        redisTemplate.delete(ORDER_KEY + orderInfo.getOrderNo());
    }
}
